package com.itphy.security;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public TokenAuthenticationFilter() {
        super("/go");//拦截的请求url
        super.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/toLogin"));//校验失败后跳转的url
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        //从request中获取token
        UsernamePasswordAuthenticationToken usernamePassword=new UsernamePasswordAuthenticationToken(getCookie(request, "token"),"");
        usernamePassword.setDetails(authenticationDetailsSource.buildDetails(request));
        return this.getAuthenticationManager().authenticate(usernamePassword);
    }

    private String getCookie(HttpServletRequest request,String key){
        Cookie[] cookies = request.getCookies();
        if(Objects.isNull(cookies)){
            return null;
        }
        for (int i = 0; i < cookies.length; i++) {
            if (key.equals(cookies[i].getName())) {
                return cookies[i].getValue();
            }
        }
        return null;
    }

}